package com.nl.controller.common.service;

import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpSession;

import com.nl.controller.common.bean.DictInfo;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.web.mapper.SmsUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.interceptor.SysContext;
import com.nl.controller.common.mapper.CommonMapper;
import com.nl.controller.web.bean.SmsMgrTemplateInfo;
import com.nl.controller.web.bean.SmsOperLog;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.mapper.TimedTaskMapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

@Service
@Slf4j
public class CommonService {

    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private TimedTaskMapper taskMapper;
    @Autowired
    private SmsUserMapper userMapper;

	private  String cityId;
    /**
     * 创建日志信息
     *
     * @param type   类型 0登录  1忘记密码  2新增  3修改  4查询 5删除 6调用接口 8 审核
     * @param remark 操作说明，如新增短信项目
     * @param result 操作结果，0成功1失败
     * @param menu   填写具体二级菜单名称
     */
    public void createSmsOperLog(String type, String remark, String result, String menu) {
        try {
            HttpSession session = SysContext.getRequest().getSession();
            SmsOperLog smsOperLog = new SmsOperLog();
            SmsUsers user = (SmsUsers) session.getAttribute("user");
            if (user != null) {
                smsOperLog.setMsisdn(user.getMsisdn());
                smsOperLog.setUserName(user.getUserName());
                smsOperLog.setDuty(user.getDuty());
                smsOperLog.setGroupName(this.getGroupName(user));
                smsOperLog.setFunctionName(menu);
                smsOperLog.setType(type);
                smsOperLog.setRemark(remark);
                smsOperLog.setResult(result);
                log.info("smsOperLog:{}", smsOperLog.toString());
                commonMapper.createSmsOperLog(smsOperLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("日志插入异常1，不抛出继续在走完流程");
        }
    }


    /**
     * 创建日志信息
     *
     * @param type   类型 0登录  1忘记密码  2新增  3修改  4查询 5删除 6调用接口 8 审核
     * @param remark 操作说明，如新增短信项目
     * @param result 操作结果，0成功1失败
     * @param menu   填写具体二级菜单名称
     */
    public void createSmsOperLogUpward(String type, String remark, String result, String menu,String opertorTel) {
        try {
            SmsOperLog smsOperLog = new SmsOperLog();
            Map<String,Object> map = new HashMap<>();
            List<SmsUsers> list = new ArrayList<>();
            map.put("msisdn",opertorTel);
            SmsUsers user = new SmsUsers();
            list = userMapper.findUser(map);
            if(!CollectionUtils.isEmpty(list)){
                user = list.get(0);
            }
            if (user != null) {
                smsOperLog.setMsisdn(user.getMsisdn());
                smsOperLog.setUserName(user.getUserName());
                smsOperLog.setDuty(user.getDuty());
                smsOperLog.setGroupName(this.getGroupName(user));
                smsOperLog.setFunctionName(menu);
                smsOperLog.setType(type);
                smsOperLog.setRemark(remark);
                smsOperLog.setResult(result);
                log.info("smsOperLog:{}", smsOperLog.toString());
                commonMapper.createSmsOperLog(smsOperLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("日志插入异常1，不抛出继续在走完流程");
        }
    }

    /**
     * 创建日志信息,采集登陆日志
     *
     * @param user   登录对象实体
     * @param type   类型 0登录  1忘记密码  2新增  3修改  4查询 5删除 6调用接口
     * @param remark 操作说明，如新增短信项目
     * @param result 操作结果，0成功1失败
     * @param menu   填写具体二级菜单名称
     */
    public void createSmsOperLog(SmsUsers user,
                                 String type, String remark, String result, String menu) {
        try {
            SmsOperLog smsOperLog = new SmsOperLog();
            smsOperLog.setMsisdn(user.getMsisdn());
            smsOperLog.setUserName(user.getUserName());
            smsOperLog.setDuty(user.getDuty());
            smsOperLog.setGroupName(this.getGroupName(user));
            smsOperLog.setFunctionName(menu);
            smsOperLog.setType(type);
            smsOperLog.setRemark(remark);
            smsOperLog.setResult(result);
            log.info("smsOperLog:{}", smsOperLog.toString());
            commonMapper.createSmsOperLog(smsOperLog);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("日志插入异常2，不抛出继续在走完流程");
        }
    }

    /**
     * 获取项目名称
     *
     * @param user 登录对象实体
     * @return 归属组，如级别是省公司管理员，归属省公司，
     * 如地市管理员则归属具体地市，如项目经理则归属具体什么项目，可能多个项目
     */
    private String getGroupName(SmsUsers user) {
        String groupName = "";
        if ("0".equals(user.getDuty())) {
            groupName = "省公司管理员";
        } else if ("1".equals(user.getDuty())) {
            groupName = "地市管理员";
        } else if ("2".equals(user.getDuty())) {
            List<Integer> mgrlist = Arrays.asList(user.getMgrId().split(","))
                    .stream().map(s -> Integer.parseInt(s.trim()))
                    .collect(Collectors.toList());
            
            List<String> list = commonMapper.getMgrName(mgrlist);
            for (String str : list) {
                groupName += str;
            }
        } else if ("3".equals(user.getDuty())) {
            groupName = "区县管理员";
        } else {
            groupName = "系统管理员";
        }
        return groupName;
    }

    @SystemServiceLog(description = "获取模板审核需要发送的管理员号码", value = false)
    public String[] templateNotice(String id) {
        String msisdn = "";
        try {
            msisdn = commonMapper.templateNotice(id);
            log.info("获取模板审核需要发送的管理员号码");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取模板审核需要发送的管理员号码");
        }
        return msisdn.split(",");
    }
    @SystemServiceLog(description = "获取模板审核需要发送的管理员号码", value = false)
    public String[] checkNum(String id) {
        String msisdn = "";
        try {
            msisdn = taskMapper.findCheckNum(id);
            log.info("获取模板审核需要发送的管理员号码");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取模板审核需要发送的管理员号码");
        }
        return msisdn.split(",");
    }
    
    @SystemServiceLog(description = "项目名称联想", value = false)
    public List<SmsMgrTemplateInfo> selectMgrNameLike(String key,String cityId,String countyId){
        List<SmsMgrTemplateInfo> list= commonMapper.selectMgrNameLike(key,cityId,countyId);
        return list;
    }
    /**
     * desc 转换为气象局地市编码
     * @author zhangh
     * @param cityId
     * @return
     */
    public String toQXJCityId(String cityId){
    	String qxjCityId = "";
    	try {
			qxjCityId = commonMapper.toQXJCityId(cityId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.toString());
		}
    	return qxjCityId;
    }
    
    
    /**
     * desc 转换为应急短信地市编码
     * @author zhangh
     * @param cityId
     * @return
     */
    public String toYJCityId(String cityId){
    	String yjCityId = "";
    	try {
    		yjCityId = commonMapper.toYJCityId(cityId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.toString());
		}
    	return yjCityId;
    }
    /**
     * desc 根据地市名称获取地市编码
     * @author zhangh
     * @param cityName
     * @return
     */
    public String toCityId(String cityName){
    	String cityId = commonMapper.toCityId(cityName);
    	return cityId;
    }

    public List<DictInfo> qryDict(String dictId){
        List<DictInfo> dictInfos = null;
        try {
            dictInfos = commonMapper.qryDict(dictId);
        } catch (Exception e) {
            throw new SmsException("查询字典信息异常："+e.getMessage());
        }
        return dictInfos;
    }

}
